package com.ruoyi.doctor.task;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
import com.ruoyi.doctor.mapper.DoctorMapper; // 假设您有一个 DoctorMapper


@Component
public class DoctorFollowSyncTask {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private DoctorMapper doctorMapper; // 您需要有一个操作 doctor 表的 Mapper

    private ObjectMapper objectMapper = new ObjectMapper();

    // 每分钟执行一次，扫描 Redis 中到期的同步任务
    @Scheduled(cron = "0 * * * * ?") // 每分钟的第 0 秒执行
    public void syncFollowCountToDatabase() {
        long now = System.currentTimeMillis() / 1000;
        String zsetKey = "doctor:follow:delay:sync";

        // 获取所有 score <= now 的任务（即到期任务）
        Set<String> tasks = redisTemplate.opsForZSet().rangeByScore(zsetKey, 0, now);

        if (tasks == null || tasks.isEmpty()) {
            return;
        }

        for (String taskJson : tasks) {
            try {
                // 解析任务
                Map<String, Object> task = objectMapper.readValue(taskJson, HashMap.class);

                Long doctorId = Long.valueOf(task.get("doctorId").toString());
                Integer changeCount = Integer.valueOf(task.get("changeCount").toString());

                // 1. 更新数据库中的 doctor.followCount 字段
                doctorMapper.increaseFollowCount(doctorId, changeCount);

                // 2. 同步成功后，从 ZSET 中移除该任务
                redisTemplate.opsForZSet().remove(zsetKey, taskJson);

                System.out.println("同步医生关注量成功：doctorId=" + doctorId + ", change=" + changeCount);

            } catch (Exception e) {
                e.printStackTrace();
                // TODO：可记录日志或加入重试机制
            }
        }
    }
}